<template>
  <view class="container">
    <view class="header">
      <view class="title">招投标管理系统</view>
      <view class="subtitle">采购方管理控制台</view>
    </view>
    
    <view class="stats-grid">
      <view class="stat-card" @click="navigateTo('/pages/auctions/list')">
        <view class="stat-icon" style="background-color: #e6f7ff;">
          <text class="iconfont icon-auction"></text>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ stats.auctionCount }}</view>
          <view class="stat-label">采购单总数</view>
        </view>
      </view>
      
      <view class="stat-card" @click="navigateTo('/pages/auctions/list?status=bidding')">
        <view class="stat-icon" style="background-color: #fffbe6;">
          <text class="iconfont icon-bidding"></text>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ stats.biddingCount }}</view>
          <view class="stat-label">竞价中</view>
        </view>
      </view>
      
      <view class="stat-card" @click="navigateTo('/pages/auctions/list?status=finished')">
        <view class="stat-icon" style="background-color: #f9f0ff;">
          <text class="iconfont icon-finished"></text>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ stats.finishedCount }}</view>
          <view class="stat-label">已结束</view>
        </view>
      </view>
      
      <view class="stat-card" @click="navigateTo('/pages/bids/list')">
        <view class="stat-icon" style="background-color: #e6fffb;">
          <text class="iconfont icon-bid"></text>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ stats.bidCount }}</view>
          <view class="stat-label">报价总数</view>
        </view>
      </view>
    </view>
    
    <view class="section">
      <view class="section-header">
        <view class="section-title">近期活动</view>
        <view class="section-action">
          <button class="section-btn" @click="navigateTo('/pages/auctions/list')">查看全部</button>
        </view>
      </view>
      
      <view class="activity-list">
        <view class="activity-item" v-for="(item, index) in recentActivities" :key="index">
          <view class="activity-icon" :class="item.type">
            <text class="iconfont" :class="getActivityIcon(item.type)"></text>
          </view>
          <view class="activity-content">
            <view class="activity-title">{{ item.title }}</view>
            <view class="activity-desc">{{ item.desc }}</view>
            <view class="activity-time">{{ formatDate(item.time) }}</view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="section">
      <view class="section-header">
        <view class="section-title">快捷操作</view>
      </view>
      
      <view class="quick-actions">
        <view class="action-item" @click="navigateTo('/pages/auctions/add')">
          <view class="action-icon" style="background-color: #e6f7ff;">
            <text class="iconfont icon-add-auction"></text>
          </view>
          <view class="action-label">发布采购单</view>
        </view>
        
        <view class="action-item" @click="navigateTo('/pages/auctions/list')">
          <view class="action-icon" style="background-color: #fffbe6;">
            <text class="iconfont icon-manage-auction"></text>
          </view>
          <view class="action-label">管理采购单</view>
        </view>
        
        <view class="action-item" @click="navigateTo('/pages/bids/list')">
          <view class="action-icon" style="background-color: #f9f0ff;">
            <text class="iconfont icon-manage-bid"></text>
          </view>
          <view class="action-label">查看报价</view>
        </view>
        
        <view class="action-item" @click="navigateTo('/pages/auctions/list?status=finished')">
          <view class="action-icon" style="background-color: #e6fffb;">
            <text class="iconfont icon-award"></text>
          </view>
          <view class="action-label">授标管理</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  const db = uniCloud.database()
  
  export default {
    data() {
      return {
        stats: {
          auctionCount: 0,
          biddingCount: 0,
          finishedCount: 0,
          bidCount: 0
        },
        recentActivities: []
      }
    },
    onLoad() {
      this.loadStats()
      this.loadRecentActivities()
    },
    methods: {
      /**
       * 加载统计数据
       */
      async loadStats() {
        try {
          // 采购单总数
          const auctionRes = await db.collection('auctions').count()
          this.stats.auctionCount = auctionRes.result.total
      
          // 竞价中的采购单
          const biddingRes = await db.collection('auctions').where('status == "bidding"').count()
          this.stats.biddingCount = biddingRes.result.total
          
          // 已结束的采购单
          const finishedRes = await db.collection('auctions').where('status == "finished"').count()
          this.stats.finishedCount = finishedRes.result.total
          
          // 报价总数
          const bidRes = await db.collection('bids').count()
          this.stats.bidCount = bidRes.result.total
        } catch (err) {
          console.error('加载统计数据失败:', err)
        }
      },
      
      /**
       * 加载近期活动
       */
      async loadRecentActivities() {
        try {
          // 获取最近的采购单
          const auctionRes = await db.collection('auctions')
            .orderBy('create_time desc')
            .limit(5)
            .get()
          
          const auctions = auctionRes.result.data || []
          
          // 获取最近的报价
          const bidRes = await db.collection('bids')
            .orderBy('timestamp desc')
            .limit(5)
            .get()
            
          const bids = bidRes.result.data || []
          
          // 合并并排序活动
          const activities = []
          
          auctions.forEach(auction => {
            activities.push({
              type: 'auction',
              title: '新增采购单',
              desc: auction.title,
              time: auction.create_time,
              id: auction._id
            })
          })
          
          bids.forEach(bid => {
            activities.push({
              type: 'bid',
              title: '新增报价',
              desc: `报价金额: ¥${bid.amount}`,
              time: bid.timestamp,
              id: bid._id
            })
          })
          
          // 按时间排序
          this.recentActivities = activities
            .sort((a, b) => b.time - a.time)
            .slice(0, 5)
        } catch (err) {
          console.error('加载近期活动失败:', err)
        }
      },
      
      /**
       * 获取活动图标
       */
      getActivityIcon(type) {
        const iconMap = {
          'auction': 'icon-auction',
          'bid': 'icon-bid'
        }
        return iconMap[type] || 'icon-default'
      },
      
      /**
       * 格式化日期
       */
      formatDate(timestamp) {
        if (!timestamp) return ''
        const date = new Date(timestamp)
        const now = new Date()
        const diff = now - date
        
        // 如果是今天
        if (date.toDateString() === now.toDateString()) {
          return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
        }
        
        // 如果是昨天
        const yesterday = new Date(now)
        yesterday.setDate(yesterday.getDate() - 1)
        if (date.toDateString() === yesterday.toDateString()) {
          return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
        }
        
        // 其他情况
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      },
      
      /**
       * 页面跳转
       */
      navigateTo(url) {
        uni.navigateTo({
          url
        })
      }
    }
  }
</script>

<style scoped>
  .container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
  }
  
  .header {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
  }
  
  .subtitle {
    font-size: 16px;
    color: #666;
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .stat-card {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    cursor: pointer;
    transition: all 0.3s;
  }
  
  .stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
  }
  
  .iconfont {
    font-size: 24px;
  }
  
  .stat-info {
    flex: 1;
  }
  
  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 14px;
    color: #666;
  }
  
  .section {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .section-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }
  
  .section-btn {
    padding: 8px 16px;
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .activity-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .activity-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-radius: 6px;
    background-color: #fafafa;
  }
  
  .activity-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
  }
  
  .activity-icon.auction {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .activity-icon.bid {
    background-color: #fffbe6;
    color: #faad14;
  }
  
  .activity-content {
    flex: 1;
  }
  
  .activity-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
  }
  
  .activity-desc {
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
  }
  
  .activity-time {
    font-size: 12px;
    color: #999;
  }
  
  .quick-actions {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
  }
  
  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
  }
  
  .action-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
  }
  
  .action-label {
    font-size: 14px;
    color: #333;
  }
  
  /* 响应式设计 */
  @media (max-width: 768px) {
    .stats-grid {
      grid-template-columns: 1fr;
    }
    
    .quick-actions {
      grid-template-columns: repeat(2, 1fr);
    }
  }
</style>